package cn.bearspark.gateway.handler;

import cn.bearspark.common.enumeration.RespCodeEnum;
import cn.bearspark.gateway.exception.NoTokenException;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 没有 token 的异常的处理器
 *
 * @author f
 * @see cn.bearspark.gateway.exception.NoTokenException
 */
public class NoTokenExceptionHandler extends DefaultErrorWebExceptionHandler {

    public NoTokenExceptionHandler(ErrorAttributes errorAttributes, WebProperties.Resources resources,
                                   ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resources, errorProperties, applicationContext);
    }

    @Override
    protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
        Throwable error = getError(request);
        // 如果不是没有 token 的异常，则交给其父类解决
        if (!(error instanceof NoTokenException)) {
            return super.renderErrorResponse(request);
        }

        // 返回失败响应
        Map<String, Object> responseBodyMap = new HashMap<>();
        responseBodyMap.put("code", RespCodeEnum.NO_TOKEN.getCode());
        responseBodyMap.put("msg", null);
        responseBodyMap.put("data", null);
        return ServerResponse
                .status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(responseBodyMap));
    }
}
